package com.zjsru.oneday202208;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: likew
 * @Date: 2022/9/7
 * 重新排列单词间的空格
 *
 * 输入：text = "  this   is  a sentence "
 * 输出："this   is   a   sentence"
 * 解释：总共有 9 个空格和 4 个单词。可以将 9 个空格平均分配到相邻单词之间，相邻单词间空格数为：9 / (4-1) = 3 个。
 *
 */
public class ReorderSpaces {
    public String reorderSpaces(String text) {
        int len = text.length(), cnt = 0;
        List<String> list = new ArrayList<>();
        for (int i = 0; i < len;) {
            if(text.charAt(i) == ' ' && ++i > 0 && ++cnt > 0){
                continue;
            }
            int j = i;
            while(j < len && text.charAt(j) != ' '){
                j++;
            }
            list.add(text.substring(i,j));
            i = j;
        }
        StringBuilder sb = new StringBuilder();
        int size = list.size();
        int t = cnt/Math.max(size-1,1);
        String k = "";
        while(t-- > 0){
            k += " ";
        }
        for (int i = 0; i < size; i++) {
            sb.append(list.get(i));
            //最后一个单词特殊处理
            if(i != size -1){
                sb.append(k);
            }
        }
        //长度不对等说明还有空格，用while循环将剩余的空格补齐
        while(sb.length() != len){
            sb.append(" ");
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        ReorderSpaces reorderSpaces = new ReorderSpaces();
        String text = "  this   is  a sentence ";
        System.out.println(reorderSpaces.reorderSpaces(text));
    }
}
